import * as React from 'react'
import { Capsule } from '../Capsule/Capsule'
import style from './style.module.less'
import { useEffect, useRef, useState } from 'react'
import axios from 'axios'
import { store } from '../../mobx/Store'
import { Observer } from 'mobx-react'
import { Link } from 'react-router-dom'

function Open() {
  const [id, setId] = useState<string>('')
  const [capsule, setCapsule] = useState<Capsule>({
    content: '',
    email: '',
    name: '',
    tip: '',
    time: '',
  })
  const [time, setTime] = useState<number>(0)
  const [timeAction, setTimeAction] = useState<boolean>(false)

  const [resultOne, setResultOne] = useState<boolean>(false)
  const [resultTwo, setResultTwo] = useState<boolean>(false)
  const [resultThree, setResultThree] = useState<boolean>(false)

  const timeRef = useRef(capsule.time)
  timeRef.current = capsule.time

  function open() {
    fetchData().then((r) => null)
  }

  useEffect(() => {
    let timer: any
    if (timeAction) {
      timer = setInterval(() => {
        setTime(
          (new Date(timeRef.current).getTime() -
            Date.now() -
            ((new Date(timeRef.current).getTime() - Date.now()) % 1000)) /
            1000,
        )
      }, 1000)
    }
    return () => clearInterval(timer)
  }, [timeAction])

  const fetchData = async () => {
    let res = await axios.post('/api/get', JSON.stringify({ id: id }))
    let response = await res.data
    setCapsule(response)
    add(response)
  }

  function add(res: any) {
    if (id === '') {
      setResultOne(false)
      setResultTwo(false)
      setResultThree(false)
    } else {
      if (res.stat === undefined) {
        if (Date.now() - new Date(timeRef.current).getTime() >= 0) {
          setResultOne(false)
          setResultTwo(false)
          setResultThree(true)
        } else {
          setResultOne(false)
          setResultTwo(true)
          setTimeAction(true)
          setResultThree(false)
        }
      } else {
        setResultOne(true)
        setResultTwo(false)
        setResultThree(false)
      }
    }
  }

  return (
    <div>
      <header className={style.top}>
        <div className={style.top_main}>
          <Link className={style.top_img} to="/">
            时间胶囊
          </Link>
          <div>
            <Link className={style.top_back} to="/">
              首页
            </Link>
            <Link className={style.top_put} to="/put">
              添加
            </Link>
            <Link className={style.top_open} to="/open">
              打开
            </Link>
          </div>
          <div className={style.changColor} onClick={() => store.setClick()}>
            更换主题
          </div>
        </div>
      </header>
      <div className={style.container}>
        <h1 className={style.page_header}>打开胶囊</h1>
        <div className={style.main}>
          <label>
            胶囊Key：
            <input
              className={style.key}
              onChange={(e) => {
                setId(e.target.value)
              }}
              style={{ width: '220px' }}
              type="text"
            />
            <Observer>
              {() => (
                <>
                  {store.click ? (
                    <input
                      className={style.formButton}
                      type="button"
                      onClick={() => open()}
                      style={{ padding: '7px' }}
                      value="打开胶囊"
                    />
                  ) : (
                    <input
                      className={style.formButtonChange}
                      type="button"
                      onClick={() => open()}
                      style={{ padding: '7px' }}
                      value="打开胶囊"
                    />
                  )}
                </>
              )}
            </Observer>
          </label>
          {resultOne ? (
            <div className={style.keyNone}>没有这个胶囊Key</div>
          ) : (
            <></>
          )}
          {resultTwo ? (
            <div className={style.keyEarlyPill}>
              <div className={style.keyPillTitle}>
                这颗胶囊未到提取时间，不能打开。
              </div>
              <div className={style.keyPillCon}>
                打开时间在<b>{capsule?.time}</b>，距离现在
                <span>
                  <b>{time}</b>
                </span>
                秒
              </div>
              <div className={style.keyPillTips}>
                {capsule?.name} 给你留的提示信息 {capsule?.tip}
              </div>
            </div>
          ) : (
            <></>
          )}
          {resultThree ? (
            <div>
              <div className={style.keyOkTitle}>
                {capsule?.name} 在 {capsule?.time} 对你说:{' '}
              </div>
              <div className={style.keyOkCon}>{capsule?.content}</div>
            </div>
          ) : (
            <></>
          )}
        </div>
      </div>
    </div>
  )
}

export default Open
